<?php

namespace App\Services;


use EasyWeChat\Kernel\Contracts\EventHandlerInterface;
use Illuminate\Cache\CacheManager;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class ImageMessageService implements EventHandlerInterface
{

    protected $action,$content,$param;

    public function handle($payload = null)
    {

        $this->initParam($payload);
        return $this->action();
    }


    public function action()
    {

        switch ($this->action){
            case 'compress':{
                return $this->param;
            }
            case 'base64':{

                $content = file_get_contents($this->param);
                return $content;
             //   return $content;
            }


        }
        $command ='php '.base_path().'/../min/index.php';
        $command .= ' compress '.$this->param;
        $this->shell($command);
        return $this->bosUrl();
    }


    public function setAction()
    {

        app('cache')->put('action',$this->action);
        return '进入'.$this->action.'模式';
    }

    public function genPath()
    {

        return bin2hex($this->param).'.png';
    }

    public function bosUrl()
    {
        $str = $this->genPath($this->param);
        $str = 'https://collect.cdn.bcebos.com/'.$this->action.'/'.$str;
        return $str;
    }
    public function shell($command)
    {

        $descriptorspec = array(
            0 => array("pipe", "r"),  // 标准输入，子进程从此管道中读取数据
            1 => array("pipe", "w"),  // 标准输出，子进程向此管道中写入数据
            2 => array("file", base_path()."/error-output.txt", "a") // 标准错误，写入到一个文件
        );
        $process = proc_open($command, $descriptorspec, $pipes);
    }





    public function initParam($payload)
    {

        $this->action = app('cache')->get('action');
        $this->param = $payload['PicUrl'];
    }




}
